package cn.wolfcode.shop.websocketserver.mq;

import cn.wolfcode.shop.websocketserver.ws.WebSocketServer;
import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class OrderListener {

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "ORDER_RESULT_NOTIFY_QUEUE"),
            exchange = @Exchange(name = "ORDER_RESULT_EXCHANGE",type = "topic"),
            key = "ORDER.*"
    ))
    public void HandlerOrderResultNotifyQueue(@Payload Map<String,Object> parma, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag, Channel channel) throws IOException {
        try {
            TimeUnit.SECONDS.sleep(1);
            String  uuid = (String) parma.get("uuid");
            WebSocketServer webSocketServer = WebSocketServer.clients.get(uuid);
            if (webSocketServer!=null){
                webSocketServer.getSession().getBasicRemote().sendText(JSON.toJSONString(parma));
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            channel.basicReject(deliveryTag,false);
        }
    }
}
